<template>
  <div class="page-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Document /></el-icon>
          <span>考试管理</span>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            添加考试
          </el-button>
        </div>
      </template>

      <el-table 
        :data="exams" 
        style="width: 100%"
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="name" label="考试名称" min-width="150" />
        <el-table-column prop="exam_id" label="考试编号" width="120" />
        <el-table-column prop="exam_time" label="考试时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.exam_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="student_count" label="考试人数" width="100" />
        <el-table-column prop="supervisor_count" label="监考人数" width="100">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.supervisor_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="editExam(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteExam(scope.row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑考试对话框 -->
    <el-dialog 
      :title="isEdit ? '编辑考试' : '添加考试'"
      v-model="showAddDialog"
      width="600px"
    >
      <el-form :model="examForm" :rules="examRules" ref="examFormRef" label-width="120px">
        <el-form-item label="考试名称" prop="name">
          <el-input v-model="examForm.name" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="考试编号" prop="exam_id">
          <el-input v-model="examForm.exam_id" placeholder="请输入考试编号" />
        </el-form-item>
        <el-form-item label="考试时间" prop="exam_time">
          <el-date-picker
            v-model="examForm.exam_time"
            type="datetime"
            placeholder="选择考试时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="考试人数" prop="student_count">
          <el-input-number 
            v-model="examForm.student_count" 
            :min="1"
            :max="1000"
            placeholder="请输入考试人数"
            style="width: 100%"
            @change="calculateSupervisorCount"
          />
        </el-form-item>
        <el-form-item label="监考人数">
          <el-input-number 
            v-model="supervisorCount" 
            :disabled="true"
            style="width: 100%"
          />
          <div class="form-tip">根据公式 M=⌊N/20⌋+1 自动计算</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveExam">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Document, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { examApi } from '@/api/exam'

interface Exam {
  id?: number
  name: string
  exam_id: string
  exam_time: string
  student_count: number
  supervisor_count: number
}

const exams = ref<Exam[]>([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const examFormRef = ref<FormInstance>()

const examForm = reactive<Exam>({
  name: '',
  exam_id: '',
  exam_time: '',
  student_count: 0,
  supervisor_count: 0
})

const examRules = {
  name: [
    { required: true, message: '请输入考试名称', trigger: 'blur' }
  ],
  exam_id: [
    { required: true, message: '请输入考试编号', trigger: 'blur' }
  ],
  exam_time: [
    { required: true, message: '请选择考试时间', trigger: 'change' }
  ],
  student_count: [
    { required: true, message: '请输入考试人数', trigger: 'blur' }
  ]
}

const supervisorCount = computed(() => {
  return Math.floor(examForm.student_count / 20) + 1
})

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const calculateSupervisorCount = () => {
  examForm.supervisor_count = supervisorCount.value
}

const loadExams = async () => {
  try {
    exams.value = await examApi.getExams()
  } catch (error) {
    ElMessage.error('加载考试列表失败')
  }
}

const resetForm = () => {
  examForm.name = ''
  examForm.exam_id = ''
  examForm.exam_time = ''
  examForm.student_count = 0
  examForm.supervisor_count = 0
  isEdit.value = false
  delete examForm.id
}

const editExam = (exam: Exam) => {
  Object.assign(examForm, exam)
  isEdit.value = true
  showAddDialog.value = true
}

const saveExam = async () => {
  if (!examFormRef.value) return
  
  try {
    await examFormRef.value.validate()
    
    examForm.supervisor_count = supervisorCount.value
    
    if (isEdit.value && examForm.id) {
      await examApi.updateExam(examForm.id, examForm)
      ElMessage.success('考试信息更新成功')
    } else {
      await examApi.createExam(examForm)
      ElMessage.success('考试添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
    loadExams()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const deleteExam = async (exam: Exam) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除考试 ${exam.name} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    if (exam.id) {
      await examApi.deleteExam(exam.id)
      ElMessage.success('删除成功')
      loadExams()
    }
  } catch (error) {
    // 用户取消删除
  }
}

onMounted(() => {
  loadExams()
})
</script>

<style scoped>
.page-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  justify-content: space-between;
}

.header-icon {
  color: #409EFF;
  font-size: 18px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

:deep(.el-table) {
  background-color: transparent;
}

:deep(.el-table tr) {
  background-color: transparent;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: rgba(0, 0, 0, 0.02);
}

:deep(.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
</style>
